package org.lq.sm.view.goods;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.lq.sm.entity.Dictionary;
import org.lq.sm.entity.Goods;
import org.lq.sm.entity.TypeID;
import org.lq.sm.service.DictionaryService;
import org.lq.sm.service.GoodsService;
import org.lq.sm.service.iml.DictionaryServiceImpl;
import org.lq.sm.service.iml.GoodsServiceImpl;
import org.lq.sm.util.CastUtil;

public class V_goods extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private static JTable table;
	private JTextField txt_query;
	private JTree tree;
	private GoodsService gs = new GoodsServiceImpl();
	private JCheckBox ck_greater;
	private int goodsId; //全局变量
	/**
	 * 获取选中商品的id
	 * @return
	 */
	public int getGoodsId() {
		return goodsId;
	}
	public V_goods(String text) {
		this();
		initTable(gs.query(text));
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					V_goods frame = new V_goods();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public V_goods() {
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 974, 577);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "\u5546\u54C1\u64CD\u4F5C", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		contentPane.add(panel, BorderLayout.NORTH);

		JLabel label = new JLabel("条码\\名称\\拼音:");
		panel.add(label);

		txt_query = new JTextField();
		panel.add(txt_query);
		txt_query.setColumns(10);

		JButton button = new JButton("查询");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//正则表达式
				String value = txt_query.getText();
				List<Goods> list = gs.query(value);
				initTable(list);
			}
		});
		button.setIcon(new ImageIcon(V_goods.class.getResource("/images/search.png")));
		panel.add(button);

		JButton button_1 = new JButton("全部商品");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				initTable(gs.findAll());
				txt_query.setText("");
			}
		});
		panel.add(button_1);

		ck_greater = new JCheckBox("只显示库存大于0");
		panel.add(ck_greater);

		JButton button_2 = new JButton("添加商品");
		
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				V_goodsAdd add = new V_goodsAdd();
				add.setBounds(V_goods.this.getX(), V_goods.this.getY(), add.getWidth(), add.getHeight());
				add.setVisible(true);
			}
		});
		
		panel.add(button_2);

		JSplitPane splitPane = new JSplitPane();
		contentPane.add(splitPane, BorderLayout.CENTER);

		tree = new JTree();
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
				List<Goods> list = null;
				if(!"商品类别".equals(dmt.toString())) {
					Dictionary d = (Dictionary) dmt.getUserObject();
					list = gs.findGoodsByCategoryID(d.getId());
				}else {
					list = gs.findAll();
				}
				initTable(list);
			}
		});
		splitPane.setLeftComponent(tree);

		JScrollPane scrollPane = new JScrollPane();
		splitPane.setRightComponent(scrollPane);

		table = new JTable();
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u7F16\u53F7", "\u540D\u79F0", "\u552E\u4EF7", "\u5E93\u5B58", "\u79EF\u5206", "min","max","id"
			}
		));
		table.getColumnModel().getColumn(5).setPreferredWidth(1);
		table.getColumnModel().getColumn(5).setMinWidth(0);
		table.getColumnModel().getColumn(5).setMaxWidth(1);
		table.getColumnModel().getColumn(6).setMinWidth(1);
		table.getColumnModel().getColumn(6).setMaxWidth(1);
		table.getColumnModel().getColumn(7).setPreferredWidth(1);
		table.getColumnModel().getColumn(7).setMinWidth(0);
		table.getColumnModel().getColumn(7).setMaxWidth(1);
		
		JPopupMenu popupMenu = new JPopupMenu();
		addPopup(table, popupMenu);
		
		JMenuItem menuItem = new JMenuItem("选择");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index = table.getSelectedRow();
				if(index >= 0) {
					goodsId =  CastUtil.castInt(table.getValueAt(index, 7));
					dispose();
				}
			}
		});
		popupMenu.add(menuItem);
		scrollPane.setViewportView(table);

		initTree();
		List<Goods> list = gs.findAll();
		initTable(list);;

		//		makeFace();
	}

	
	/**
	 * 初始化表格
	 */
	public void initTable(List<Goods> list) {

		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		int count = dtm.getRowCount();
		for(int i = 0;i<count;i++) {
			dtm.removeRow(0);
		}
		boolean selected = this.ck_greater.isSelected();
		for (Goods goods : list) {
			//只显示大于0 的
			if(selected == true && goods.getInventory()<=0) {
				continue;
			}
			dtm.addRow(new Object[] {
					goods.getGoods_number(),
					goods.getName(),
					goods.getSell_price(),
					goods.getInventory(),
					goods.getIntegral(),
					goods.getMin_inventory(),
					goods.getMax_inventory(),
					goods.getId()
			});
		}

	}

	/**
	 * 初始类型节点
	 */
	public void initTree() {
		DictionaryService ds = new DictionaryServiceImpl();
		List<Dictionary> list = ds.findDictionaryByTypeID(TypeID.类别);
		DefaultMutableTreeNode dmtn = new DefaultMutableTreeNode("商品类别");
		for (Dictionary d : list) {
			dmtn.add(new DefaultMutableTreeNode(d));
		}
		DefaultTreeModel dtm = new DefaultTreeModel(dmtn);
		tree.setModel(dtm);
	}




	/**
	 * 改变行颜色
	 */
	public void makeFace() {
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
					boolean hasFocus, int row, int column) {

				if(column == 3) {
					int min =  CastUtil.castInt(table.getValueAt(row, 5));
					int max = CastUtil.castInt(table.getValueAt(row, 6));
					int kc = CastUtil.castInt(value);
					if(kc <= min) {
						setBackground(new Color(255, 222, 173));
					}
				}

				//					setForeground(new Color(255, 222, 173));
				return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			}
		};
		//获取当前表格中的所有行
		int count = table.getColumnCount();
		for (int i = 0; i < count; i++) {
			table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
		}

	}







	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				int index= table.rowAtPoint(e.getPoint());
				table.setRowSelectionInterval(index, index);
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}
